package com.es.action.heat.exec.exectime;

import com.es.common.Cache;
import com.es.action.heat.exec.execthread.ThreadCallable;
import com.es.common.FileCache;

import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 执行策略
 *
 * @author Will
 */
public abstract class BaseStrategy {

    /**
     * 实际文件状态 ！！！是实际状态
     */
    private Map<String, Long> map;
    /**
     * 启用线程数量
     */
    private final int threadNum = (int) Cache.get("threadNum");

    public Map<String, Long> getMap() {
        return map;
    }

    public void setMap(Map<String, Long> map) {
        this.map = map;
    }

    /**
     * 运行抽象
     */
    public abstract void run();

    public void start() {

        // 多线程编译运行
        ExecutorService es = Executors.newFixedThreadPool(threadNum);

        ArrayList<Object> arrayList = new ArrayList<>();
        map.forEach((x, y) -> {
            Long time = FileCache.get(x);
            if (time == null || !time.equals(y)) {
                try {
                    arrayList.add(es.submit(new ThreadCallable(x)).get());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        es.shutdownNow();

        // 替换内存内容，即时更新数据
        arrayList.forEach(x -> {
            FileCache.addCache(x.toString(), map.get(x));
        });
    }
}
